/**
 * Created by chenshengli on 2015/6/19 0019.
 */
/**
 * Created by Administrator on 2015/2/1.
 */

var MongoClient = require('mongodb').MongoClient;
var logger = require('./logger');
var Config = require('./config');
var Fiber = require('fibers');

var mongoDB = null;
MongoClient.connect(Config.mongoURL, function (err, db) {
    if (err)logger.error("mongodb init error", err);
    mongoDB = db;
    logger.info("mongodb init~");
});


exports.find = function (collection, query, options, callback) {
    if (options == undefined) {
        options = {};
    }
    mongoDB.collection(collection).find(query, options).toArray(callback);
};


exports.findSync = function (collection, query, options) {
    var result = null;
    var fiber = Fiber.current;
    if (options == undefined) {
        options = {};
    }
    mongoDB.collection(collection).find(query, options).toArray(function (err, docs) {
        if (err)logger.error("mongodb init error", err);
        result = docs;
        if (fiber) {
            fiber.run(result);
        }
    });
    Fiber.yield();
    return result;
};


exports.findOneSync = function(collection,query, options){
    var result = null;
    if (options == undefined) {
        options = {};
    }
    var Fiber = require('fibers');
    var fiber = Fiber.current;
    mongoDB.collection(collection).findOne(query, options,function(err, doc){
        if (err)logger.error("mongodb init error", err);
        result = doc;
        if (fiber) {
            fiber.run(result);
        }
    })
    Fiber.yield();
    return result;
}

exports._insert = function (collection, obj, options, callback) {
    mongoDB.collection(collection).insert(obj, options, callback);
};


exports._updateOrInsert = function (collection, query, obj, callback) {
    mongoDB.collection(collection).update(query, {$set: obj}, {upsert: true, w: 1}, callback);
}

/**
 * 如果查询失败，将插入obj
 * @param collection
 * @param query
 * @param obj
 * @private
 */

exports._updateOnly = function (collection, query, obj, callback) {
    mongoDB.collection(collection).update(query, {$set: obj}, {w: 1}, callback);
}


exports._findAndModify = function (collection, query, sort, doc, options, callback) {
    mongoDB.collection(collection).findAndModify(query, sort, doc, options, callback);
}


exports._delete = function (collection, query, options, callback) {
    if (options == undefined) {
        options = {};
    }
    mongoDB.collection(collection).remove(query, options, callback)
}


exports._group = function (collection, keys, condition, initial, reduce, finalize, command, options, callback) {
    mongoDB.collection(collection).group(keys, condition, initial, reduce, finalize, command, options, callback);
}